using Lcygcc.Infrastructure.Logs;
using Lcygcc.Infrastructure.Repository;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Data.Entity.Infrastructure;
using System.Data.Entity.Validation;
using System.Linq;
namespace Lcygcc.Domain.Repository.Entity
{
	public class EfRepository<T> : IRepository<T> where T : class, new()
	{
		private static int m_pageSize;
		public static int pageSize
		{
			get
			{
				try
				{
					if (EfRepository<T>.m_pageSize == 0)
					{
						int num = 100;
						if (num > 0 && num <= 10000)
						{
							EfRepository<T>.m_pageSize = num;
						}
						else
						{
							EfRepository<T>.m_pageSize = 10000;
						}
					}
				}
				catch (Exception ex)
				{
					EfRepository<T>.m_pageSize = 10000;
                    Logger.Error("----EfRepository----", ex);
                }
				return EfRepository<T>.m_pageSize;
			}
		}
		public SqlSugarClient _context
		{
			get
			{
				return new BaseRepository().db;
			}
		}
		protected SqlSugarClient _debug_context
		{
			get
			{
				return new BaseRepository().db;
			}
		}
		public SqlSugarClient db
		{
			get
			{
				return new BaseRepository().db;
			}
		}
		[Obsolete("提示：该方法已期，请使用 Queryable！")]
		public virtual ISugarQueryable<T> Table
		{
			get
			{
				return this._context.Queryable<T>();
			}
		}
		public virtual IQueryable<T> TableNoTracking
		{
			get
			{
				return null;
			}
		}
		private bool TSupportDebugModule(T entity)
		{
			Type typeFromHandle = typeof(T);
			object[] customAttributes = typeFromHandle.GetCustomAttributes(typeof(DebugModuleAttribute), true);
			bool result;
			if (0 == customAttributes.Count<object>())
			{
				result = false;
			}
			else
			{
				DebugModuleAttribute debugModuleAttribute = customAttributes[0] as DebugModuleAttribute;
				result = debugModuleAttribute.Debug;
			}
			return result;
		}
		private bool TSupportBroadCastModule(T entity)
		{
			Type typeFromHandle = typeof(T);
			object[] customAttributes = typeFromHandle.GetCustomAttributes(typeof(DebugModuleAttribute), true);
			bool result;
			if (0 == customAttributes.Count<object>())
			{
				result = false;
			}
			else
			{
				DebugModuleAttribute debugModuleAttribute = customAttributes[0] as DebugModuleAttribute;
				result = debugModuleAttribute.BroadCast;
			}
			return result;
		}
		private string GetServiceID()
		{
			Type typeFromHandle = typeof(T);
			object[] customAttributes = typeFromHandle.GetCustomAttributes(typeof(DebugModuleAttribute), true);
			string result;
			if (0 == customAttributes.Count<object>())
			{
				result = string.Empty;
			}
			else
			{
				DebugModuleAttribute debugModuleAttribute = customAttributes[0] as DebugModuleAttribute;
				result = debugModuleAttribute.Serviceid;
			}
			return result;
		}
		private bool IsDebugModule()
		{
			return false;
		}
		public EfRepository()
		{
		}
		public EfRepository(SqlSugarClient context, SqlSugarClient debug_context)
		{

		}
		public virtual T GetById(object id)
		{
			T result;
			try
			{
				T t = this._context.Queryable<T>().InSingle(id);
				result = t;
				return result;
			}
			catch (DbEntityValidationException ex)
			{
                Logger.Error("----EfRepository----", ex);
            }
			result = default(T);
			return result;
		}
		public virtual T Insert(T entity)
		{
			T result;
			try
			{
				if (entity == null)
				{
					throw new ArgumentNullException("entity");
				}
				int num = this._context.Context.Insertable<T>(entity).ExecuteCommand();
				if (num > 0)
				{
					BaseEntity baseEntity = entity as BaseEntity;
					if (baseEntity != null)
					{
						baseEntity.DbResult = true;
					}
					result = entity;
					return result;
				}
				result = default(T);
				return result;
			}
			catch (DbEntityValidationException ex)
			{
				throw new Exception("数据验证失败" + ex.ToString());
			}
			catch (Exception ex)
			{
                Logger.Error("----EfRepository----",ex);
			}
			result = default(T);
			return result;
		}
		public virtual void Insert(IEnumerable<T> entities)
		{
			try
			{
				int num = entities.Count<T>();
				if (num > 0)
				{
					T t = entities.First<T>();
					string text = t.GetType().ToString();
				}
				int num2 = num / EfRepository<T>.pageSize + 1;
				if (num2 > 0)
				{
					for (int i = 0; i < num2; i++)
					{
						IEnumerable<T> enumerable = entities.Skip(EfRepository<T>.pageSize * i).Take(EfRepository<T>.pageSize);
						if (enumerable == null)
						{
							throw new ArgumentNullException("entities");
						}
						if (enumerable.Count<T>() > 0)
						{
							this._context.Insertable<T>(enumerable.ToList<T>()).ExecuteCommand();
						}
					}
				}
				else
				{
					if (entities == null)
					{
						throw new ArgumentNullException("entities");
					}
					if (entities.Count<T>() > 0)
					{
						this._context.Insertable<T>(entities.ToList<T>()).ExecuteCommand();
					}
				}
			}
			catch (DbEntityValidationException ex)
			{
                Logger.Error("----EfRepository----", ex);
            }
			catch (Exception ex)
			{
                Logger.Error("----EfRepository----", ex);
            }
		}
		public virtual void Update(T entity)
		{
			try
			{
				if (entity == null)
				{
					throw new ArgumentNullException("entity");
				}
				this._context.Updateable<T>(entity).ExecuteCommand();
				BaseEntity baseEntity = entity as BaseEntity;
				if (baseEntity != null)
				{
					baseEntity.DbResult = true;
				}
			}
			catch (DbEntityValidationException ex)
			{
                Logger.Error("----EfRepository----", ex);
            }
			catch (Exception ex)
			{
                Logger.Error("----EfRepository----", ex);
            }
		}
		public void Update(IEnumerable<T> entities)
		{
			try
			{
				int num = entities.Count<T>();
				if (num > 0)
				{
					T t = entities.First<T>();
					string text = t.GetType().ToString();
				}
				int num2 = num / EfRepository<T>.pageSize + 1;
				if (num2 > 0)
				{
					for (int i = 0; i < num2; i++)
					{
						IEnumerable<T> enumerable = entities.Skip(EfRepository<T>.pageSize * i).Take(EfRepository<T>.pageSize);
						if (enumerable == null)
						{
							throw new ArgumentNullException("entities");
						}
						if (enumerable.Count<T>() > 0)
						{
							this._context.Updateable<T>(enumerable.ToList<T>()).ExecuteCommand();
						}
					}
				}
				else
				{
					if (entities == null)
					{
						throw new ArgumentNullException("entities");
					}
					if (entities.Count<T>() > 0)
					{
						this._context.Updateable<T>(entities.ToList<T>()).ExecuteCommand();
					}
				}
			}
			catch (DbEntityValidationException ex)
			{
                Logger.Error("----EfRepository----", ex);
            }
			catch (Exception ex)
			{
                Logger.Error("----EfRepository----", ex);
            }
		}
		public virtual void Delete(T entity)
		{
			try
			{
				if (entity == null)
				{
					throw new ArgumentNullException("entity");
				}
				this._context.Deleteable<T>().Where(entity).ExecuteCommand();
				BaseEntity baseEntity = entity as BaseEntity;
				if (baseEntity != null)
				{
					baseEntity.DbResult = true;
				}
			}
			catch (DbEntityValidationException ex)
			{
                Logger.Error("----EfRepository----", ex);
            }
			catch (Exception ex)
			{
                Logger.Error("----EfRepository----", ex);
            }
		}
		public virtual void Delete(IEnumerable<T> entities)
		{
			try
			{
				int num = entities.Count<T>();
				if (num > 0)
				{
					T t = entities.First<T>();
					string text = t.GetType().ToString();
				}
				int num2 = num / EfRepository<T>.pageSize + 1;
				if (num2 > 0)
				{
					for (int i = 0; i < num2; i++)
					{
						IEnumerable<T> enumerable = entities.Skip(EfRepository<T>.pageSize * i).Take(EfRepository<T>.pageSize);
						if (enumerable == null)
						{
							throw new ArgumentNullException("entities");
						}
						if (enumerable.Count<T>() > 0)
						{
							this._context.Deleteable<T>(enumerable.ToList<T>()).ExecuteCommand();
						}
					}
				}
				else
				{
					if (entities == null)
					{
						throw new ArgumentNullException("entities");
					}
					if (entities.Count<T>() > 0)
					{
						this._context.Deleteable<T>(entities.ToList<T>()).ExecuteCommand();
					}
				}
			}
			catch (DbEntityValidationException ex)
			{
                Logger.Error("----EfRepository----", ex);
            }
			catch (Exception ex)
			{
                Logger.Error("----EfRepository----", ex);
            }
		}
		private string GetDbEntityValidationExceptionString(DbEntityValidationException dbEx)
		{
			return dbEx.EntityValidationErrors.SelectMany(errors => errors.ValidationErrors)
                .Aggregate(string.Empty, 
                (current, error) => 
                current + 
                (Environment.NewLine + string.Format("Property: {0} Error: {1}", error.PropertyName, error.ErrorMessage)));
		}
		public string GetDbTime()
		{
			string result;
			try
			{
				var objectContext = ((IObjectContextAdapter)_context).ObjectContext;
				string text = objectContext.ExecuteStoreQuery<string>("SELECT NOW() as string", new object[0]).FirstOrDefault<string>();
				result = text;
			}
			catch (Exception)
			{
				result = string.Empty;
			}
			return result;
		}
		private void SendToBoxBroadCast(T entity)
		{
		}
		public IList<T> SqlQuery(string sql, params object[] parameters)
		{
			return this._context.Ado.SqlQuery<T>(sql, parameters);
		}
		public int ExecuteSqlCommand(string sql, params object[] parameters)
		{
			return this._context.Ado.ExecuteCommand(sql, parameters);
		}
		public string GetConnectionString()
		{
			return this._context.CurrentConnectionConfig.ConnectionString;
		}
	}
}
